import { ItemDat } from '../../Tools/QType';
import Db from '../../Tools/Db';
const {ccclass, property} = cc._decorator;

@ccclass
export default class ShopItem extends cc.Component {
    private nameLabel:cc.Label;
    private price:cc.Label;
    private sum:cc.Label;
    private number:cc.Label;
    private subBtn:cc.Node;
    private addBtn:cc.Node;

    private itemDat:ItemDat;

    /** 当前购买的数量 */
    private _currentNum:number=0;
    get currentNum(){
        return this._currentNum;
    }
    set currentNum(value){
        if(value<0||value>99)return;
        if(this.currentNum==value)return;
        this._currentNum = value;

        //数量变更时，
        this.CommodityShow();

        this.updateUI();
    }

    onLoad(){
        this.nameLabel = this.node.getChildByName("name").getComponent(cc.Label);
        this.price = this.node.getChildByName("price").getComponent(cc.Label);
        this.sum = this.node.getChildByName("sum").getComponent(cc.Label);
        this.number = this.node.getChildByName("number").getChildByName("value").getComponent(cc.Label);
        this.subBtn = this.node.getChildByName("number").getChildByName("sub");
        this.addBtn = this.node.getChildByName("number").getChildByName("add");
     

        this.subBtn.on(cc.Node.EventType.TOUCH_END,this.sub,this);
        this.addBtn.on(cc.Node.EventType.TOUCH_END,this.add,this)
        this.node.on(cc.Node.EventType.TOUCH_END,this.CommodityShow,this)
    }


   

    setDat(itemDat:ItemDat){
        this.itemDat = itemDat;
        this.updateUI();
    }

    updateUI(){
        this.nameLabel.string = this.itemDat.name;
        this.price.string = this.itemDat.price.toString();
        this.sum.string = (this.itemDat.price*this.currentNum).toString();
        this.number.string = this.currentNum.toString();
    }

    sub(){    
        this.currentNum--;
    }

    add(){        
        this.currentNum++;
    }
    /** 商品显示 */
    CommodityShow(){
        let e = new cc.Event.EventCustom("CommodityShow",true);
        let obj={
            item:this.itemDat,
            count:this.currentNum
        }
        e.setUserData(obj);
        this.node.dispatchEvent(e);
    }

    reset(){
        this.currentNum=0;
        this.sum.string = "0";
        this.number.string = "0";
    }
}
